﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using App.Core.Domain.BaseObject;
using App.Core.Dtos;
using App.Core.Helpers;
using App.Core;
using App.Core.DataAccess;
using System.Data.Entity;
using App.Core.Domain;
using Omu.ValueInjecter;
using System.Linq.Expressions;
using EntityFramework.Extensions;

namespace App.Services.Impls
{
    public partial class GoodsServiceImpl : AppServiceBase, IGoodsService
    {
        private readonly CurrentSession _curUser;
        public GoodsServiceImpl()
        {
            _curUser = new CurrentSession();
        }

        public async Task<OperationResult> CreateGoods(GoodsDto dto)
        {
            using (var db = new Db())
            {
                if (await db.Goods.CountAsync(t => t.GoodsName == dto.GoodsName) > 0)
                {
                    return new OperationResult() { success = false, message = string.Format("名为【{0}】的商品已经存在！", dto.GoodsName) };
                }
                var entity = new Goods();
                entity.InjectFrom(dto);
                entity.Brand = await db.GoodsBrand.FindAsync(dto.BrandId);
                if (dto.GoodsCategorys != null)
                {
                    entity.Categorys = new List<GoodsCategory>();
                    foreach (var categoryId in dto.GoodsCategorys)
                    {
                        entity.Categorys.Add(await db.GoodsCategory.FindAsync(categoryId));
                    }
                }

                db.Goods.Add(entity);
                var result = await db.SaveChangesAsync();

                return new OperationResult() { success = result > 0 };
            }
        }


        public async Task<OperationResult> UpdateGoods(Guid id, GoodsDto dto)
        {
            using (var db = new Db())
            {
                var entity = await db.Goods.Include("Categorys").SingleAsync(s=>s.Id == id);
                if (entity == null)
                {
                    return new OperationResult() { success = false, message = string.Format("找不到该记录Id为{0}的记录", id) };
                }

                entity.InjectFrom(dto);
                entity.Brand = await db.GoodsBrand.FindAsync(dto.BrandId);
                entity.Categorys.Clear();
                if (dto.GoodsCategorys != null)
                    foreach (var item in dto.GoodsCategorys)
                    {
                        entity.Categorys.Add(await db.GoodsCategory.FindAsync(item));
                    }

                var result = await db.SaveChangesAsync();

                return new OperationResult() { success = result > 0 };
            }
        }

        public async Task<OperationResult> CreateCategory(GoodsCategoryDto dto)
        {
            using (var db = new Db())
            {
                if (await db.GoodsCategory.CountAsync(t => t.CategoryName == dto.CategoryName) > 0)
                {
                    return new OperationResult() { success = false, message = string.Format("名为【{0}】的分类已经存在！", dto.CategoryName) };
                }

                var entity = new GoodsCategory();
                entity.InjectFrom(dto);

                db.GoodsCategory.Add(entity);
                var result = await db.SaveChangesAsync();

                return new OperationResult() { success = result > 0 };
            }
        }

        public List<GoodsCategory> GetCategorys(Expression<Func<GoodsCategory, bool>> predicate = null)
        {
            using (var db = new Db())
            {
                return db.GoodsCategory.ToList();
            }
        }

        public async Task<OperationResult> SaveBrands(BulkDto<BrandDto> dto)
        {
            using (var db = new Db())
            {
                var curUser = new CurrentSession();
                var exists = new List<string>();
                //批量插入
                foreach (var row in dto.InsertedRows)
                {
                    if (await db.GoodsBrand.CountAsync(b => b.BrandName == row.BrandName) > 0)
                    {
                        exists.Add(string.Format("名为【{0}】的品牌已经存在！", row.BrandName));
                    }
                    else
                    {
                        var entity = new GoodsBrand();
                        entity.InjectFrom<NotNullInjection>(row);
                        db.GoodsBrand.Add(entity);
                    }
                }
                //批量更新
                foreach (var row in dto.UpdatedRows)
                {
                    var entity = await db.GoodsBrand.FindAsync(row.Id);
                    entity.InjectFrom(new NotNullInjection(), row);
                }

                //删除
                var deleteArray = dto.DeletedRows.Where(row => row.Id != null).Select(s => s.Id).ToArray();
                if (deleteArray.Length > 0)
                {
                    await db.GoodsBrand.Where(s => deleteArray.Contains(s.Id)).DeleteAsync();
                }

                await db.SaveChangesAsync();

                return new OperationResult() { success = true, message = dto.DeletedRows.Count > 0 ? "数据已经成功删除！" : exists.Count > 0 ? String.Join("<br />", exists) : "保存成功！" };
            }
        }

        public async Task<OperationResult> UpdateCategory(Guid id, GoodsCategoryDto dto)
        {
            using (var db = new Db())
            {
                var entity = await db.GoodsCategory.FindAsync(id);
                if (entity == null)
                {
                    return new OperationResult() { success = false, message = string.Format("找不到该记录Team Id为{0}的记录", id) };
                }

                entity.InjectFrom(dto);

                var result = await db.SaveChangesAsync();

                return new OperationResult() { success = result > 0 };
            }
        }

        public async Task<Goods> GetGoods(Guid id)
        {
            using (var db = new Db())
            {
                return await db.Goods.Include("Brand").Include("Categorys").FirstOrDefaultAsync(s=>s.Id == id);
            }
        }

        public async Task DeleteAsync(Guid[] idList)
        {
            using (var db = new Db())
            {
                await db.Goods.Where(s => idList.Contains(s.Id)).DeleteAsync();
            }
        }

        public async Task DeleteCategoryAsync(Guid id)
        {
            using (var db = new Db())
            {
                await db.GoodsCategory.Where(s => s.Id == id).DeleteAsync();
            }
        }
    }
}
